using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Windows;
using Tryit.Models;

namespace Tryit.ViewModels
{
    public class TemplateEditViewModel : BindableBase
    {
        private CompositionTemplate _template;
        private ElementComposition _selectedElement;
        private Window _window;

        public CompositionTemplate Template
        {
            get => _template;
            set => SetProperty(ref _template, value);
        }

        public ElementComposition SelectedElement
        {
            get => _selectedElement;
            set => SetProperty(ref _selectedElement, value);
        }

        // 命令
        public DelegateCommand AddElementCommand { get; set; }
        public DelegateCommand DeleteElementCommand { get;set; }
        public DelegateCommand ImportDefaultElementsCommand { get; set; }
        public DelegateCommand ConfirmCommand { get; set; }
        public DelegateCommand CancelCommand { get; set; }

        public TemplateEditViewModel()
        {
            Template = new CompositionTemplate();
            InitializeCommands();
        }

        public TemplateEditViewModel(CompositionTemplate template)
        {
            Template = template ?? new CompositionTemplate();
            InitializeCommands();
        }

        public void SetWindow(Window window)
        {
            _window = window;
        }

        private void InitializeCommands()
        {
            AddElementCommand = new DelegateCommand(ExecuteAddElement);
            DeleteElementCommand = new DelegateCommand(ExecuteDeleteElement, CanExecuteDeleteElement)
                .ObservesProperty(() => SelectedElement);
            ImportDefaultElementsCommand = new DelegateCommand(ExecuteImportDefaultElements);
            ConfirmCommand = new DelegateCommand(ExecuteConfirm);
            CancelCommand = new DelegateCommand(ExecuteCancel);
        }

        private void ExecuteAddElement()
        {
            try
            {
                var element = new ElementComposition
                {
                    Name = "新元素",
                    TechnicalRequirement = "",
                    InternalRequirement = "",
                    Status = "未知"
                };

                Template.AddElement(element);
                SelectedElement = element;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加元素失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ExecuteDeleteElement()
        {
            if (SelectedElement == null) return;

            try
            {
                var result = MessageBox.Show($"确定要删除元素 '{SelectedElement.Name}' 吗？", 
                    "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Question);
                
                if (result == MessageBoxResult.Yes)
                {
                    Template.RemoveElement(SelectedElement);
                    SelectedElement = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除元素失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ExecuteImportDefaultElements()
        {
            try
            {
                var defaultTemplatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "default_composition_templates.json");
                if (!File.Exists(defaultTemplatePath))
                {
                    MessageBox.Show("默认模板文件不存在", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                var json = File.ReadAllText(defaultTemplatePath);
                var defaultElements = JsonSerializer.Deserialize<List<ElementComposition>>(json);

                if (defaultElements != null && defaultElements.Any())
                {
                    // 先清空现有元素
                    Template.Elements.Clear();

                    // 添加默认元素
                    foreach (var element in defaultElements)
                    {
                        Template.Elements.Add(element);
                    }

                    MessageBox.Show($"成功导入 {defaultElements.Count} 个默认元素", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导入默认元素失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ExecuteConfirm()
        {
            try
            {
                // 验证模板名称
                if (string.IsNullOrWhiteSpace(Template.Name))
                {
                    MessageBox.Show("请输入模板名称", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // 验证元素数据
                foreach (var element in Template.Elements)
                {
                    if (string.IsNullOrWhiteSpace(element.Name))
                    {
                        MessageBox.Show("元素名称不能为空", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }

                    // 验证技术要求格式
                    if (!string.IsNullOrWhiteSpace(element.TechnicalRequirement) && 
                        !ElementComposition.ValidateRequirementFormat(element.TechnicalRequirement))
                    {
                        MessageBox.Show($"元素 '{element.Name}' 的技术要求格式不正确", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }

                    // 验证内控要求格式
                    if (!string.IsNullOrWhiteSpace(element.InternalRequirement) && 
                        !ElementComposition.ValidateRequirementFormat(element.InternalRequirement))
                    {
                        MessageBox.Show($"元素 '{element.Name}' 的内控要求格式不正确", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                }

                // 验证状态
                Template.ValidateAllElements();

                if (_window != null)
                {
                    _window.DialogResult = true;
                    _window.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存模板失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ExecuteCancel()
        {
            if (_window != null)
            {
                _window.DialogResult = false;
                _window.Close();
            }
        }

        private bool CanExecuteDeleteElement()
        {
            return SelectedElement != null;
        }
    }
} 